import akshare as ak
import os
import time

def get_all_a_stock_history():
    # 获取所有A股股票代码和名称
    stock_list = ak.stock_info_a_code_name()
    
    # 创建保存目录
    os.makedirs('stock_data', exist_ok=True)
    
    # 遍历所有股票
    for index, row in stock_list.iterrows():
        stock_code = row['code']
        stock_name = row['name']
        
        print(f"正在下载 {stock_code}-{stock_name} 的历史数据...")
        
        try:
            # 获取股票日线数据
            df = ak.stock_zh_a_hist(
                symbol=stock_code,
                period="daily",
                start_date="19900101",  # 设置足够早的日期以获取全部数据
                end_date="22221231",    # 设置足够晚的日期
                adjust=""           # 不复权
            )
            
            if not df.empty:
                # 保存为CSV文件
                df.to_csv(f'stock_data/{stock_code}.csv', index=False)
                print(f"成功保存 {stock_code}.csv")
            else:
                print(f"无有效数据：{stock_code}")
            
            # 添加请求间隔避免被封IP
            time.sleep(0.2)
            
        except Exception as e:
            print(f"获取 {stock_code} 数据失败：{str(e)}")
            continue

if __name__ == "__main__":
    get_all_a_stock_history()
    print("全部数据下载完成！")
